<?php


namespace backend\models\c2\form;


use api\models\c2\entity\VoteRecordModel;
use common\models\c2\entity\ActivityPlayerModel;
use common\models\c2\entity\ActivityPlayerVoteRecordModel;
use common\models\c2\entity\GiftModel;
use common\models\c2\statics\VoteType;
use cza\base\models\ModelTrait;
use yii\base\Model;
use yii\helpers\ArrayHelper;

class BrushVoteForm extends Model
{
    use ModelTrait;

    public $brush_sub_ids;
    public $user_id;

    /**
     * @var ActivityPlayerModel
     */
    public $entityModel;

    public function rules()
    {
        return [
            [['user_id', 'activity_player_id', 'vote_number', 'gift_id', 'order_id'], 'integer'],
            [['created_at', 'updated_at'], 'safe'],
            [['brush_sub_ids', 'user_id',], 'required'],
            [['type', 'state', 'status'], 'integer', 'max' => 4],
            [['remote_ip', 'gift_name'], 'string', 'max' => 255],
        ];
    }

    public function attributeLabels()
    {
        return [
            'user_id' => \Yii::t('app.c2', 'Username'),
            'brush_sub_ids' => \Yii::t('app.c2', 'Brush Sub Ids'),
        ]; // TODO: Change the autogenerated stub
    }

    public function save()
    {
        foreach ($this->brush_sub_ids as $brush_sub_id) {
            $vote = new VoteRecordModel();
            if ($brush_sub_id == 0) {
                $vote->setAttributes([
                    'type' => VoteType::TYPE_SYS_FREE,
                    'vote_number' => 1,
                    'user_id' => $this->user_id,
                    'activity_player_id' => $this->entityModel->id,
                    'remote_ip' => \Yii::$app->request->userIP,
                ]);
            } else {
                $gift = GiftModel::findOne($brush_sub_id);
                if ($gift) {
                    $vote->setAttributes([
                        'type' => VoteType::TYPE_SYS_GIFT,
                        'user_id' => $this->user_id,
                        'activity_player_id' => $this->entityModel->id,
                        'gift_id' => $gift->id,
                        'gift_name' => $gift->name,
                        'vote_number' => $gift->obtain_vote_number,
                        'remote_ip' => \Yii::$app->request->userIP,
                    ]);
                }
            }
            $vote->save();
        }
    }

}